package penguin.masking;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author wuxh
 * @version 1.0.0
 */
public class StringUtil {

    public static String md5(String s) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(s.getBytes());
            byte[] digest = md5.digest();
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(Integer.toHexString(b & 0xff));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String mdfIfLong(String s) {
        if (s.length() < 50) {
            return s;
        }
        return md5(s);
    }

    public static List<String> split(String s, String regex) {
        if (isEmpty(s)) {
            return new ArrayList<>();
        }
        String[] split = s.split(regex);
        return Arrays.asList(split);
    }

    public static boolean isEmpty(String s) {
        if (s == null) {
            return true;
        }

        if ("".equals(s.trim())) {
            return true;
        }

        return false;
    }

    /**
     * 正则表达式替换，支持方法回调
     *
     * @param v
     * @param replaceStr
     * @param callBack   回调方法，匹配成功后执行
     * @return
     */
    public static String replace(String v, String replaceStr, CallBack<String, String> callBack) {
        Matcher matcher = Pattern.compile(replaceStr).matcher(v);
        boolean result = matcher.find();
        if (result) {
            StringBuffer sb = new StringBuffer();
            do {
                String replacement = callBack.call(matcher.group());
                matcher.appendReplacement(sb, replacement);
                result = matcher.find();
            } while (result);
            matcher.appendTail(sb);
            return sb.toString();
        }
        return v;
    }
}
